/*
 * @Author: fhw
 * @Date: 2022-04-21 23:18:03
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-02-02 11:03:41
 * @Description: 创建群聊
 */
import { computed, defineComponent, PropType, reactive, watch } from 'vue'
import './style.scss'
import { ContactsFriends, User } from '@/interface'
import { BasicDataModule } from '@/store/modules/basicData'
import UserImg from '@/components/user/userImg'
import { clone, equals, isEmpty, isNil, map, unnest } from 'ramda'
import { CloseCircleFilled } from '@ant-design/icons-vue'
import { errorTips, successTips } from '@/utils'
import { pySegSort } from '@/utils/PySegSort'
interface contactsData extends ContactsFriends {
	checked?: boolean
	disabled?: boolean
}
interface Contacts {
	letter: string
	data: contactsData[]
}
const props = {
	visible: {
		type: Boolean as PropType<boolean>,
		required: true,
	},
	data: {
		type: Array as PropType<User[]>,
		default: [],
	},
} as const
export default defineComponent({
	props,
	emits: ['cancel', 'submit'],
	setup(props, { emit }) {
		/** 用户id */
		const userId = localStorage.getItem('userId') as string
		/** 好友备注集合 */
		const friendsRemarksMap = computed<Map<string, string>>(() => {
			return BasicDataModule.friendsRemarksMap
		})
		const pageState = reactive({
			contacts: [] as Contacts[],
			selectFriends: [] as contactsData[],
			loading: false,
		})
		/** 监听弹窗开启 */
		watch(
			() => props.visible,
			(visible) => {
				if (visible) {
					const ids = props.data.map((item) => item.id)
					const contacts = BasicDataModule.contacts.map((item: any) => {
						const data = clone(item)
						if (ids.includes(data.friendsId)) {
							data.disabled = true
							data.checked = true
						}
						return {
							...data,
						}
					})
					pageState.contacts = pySegSort(clone(contacts.filter((item) => isNil(item.groupChat))))
				} else {
					pageState.contacts = []
				}
			}
		)
		/**
		 * 选择用户
		 * @param {object} dataSource
		 */
		function selectFriends(dataSource: contactsData) {
			if (dataSource.disabled) return
			dataSource.checked = !dataSource.checked
			if (dataSource.checked) {
				dataSource.checked = true
				pageState.selectFriends.push(dataSource)
			} else {
				delFriends(dataSource)
			}
		}
		/**
		 * 删除选中用户
		 * @param {object} dataSource
		 */
		function delFriends(dataSource: contactsData) {
			const index = pageState.selectFriends.findIndex((item) => equals(item.id, dataSource.id))
			if (equals(index, -1)) return
			dataSource.checked = false
			pageState.selectFriends.splice(index, 1)
		}
		// 获取id
		const userIds = computed(() => {
			const ids = pageState.contacts.map((item) => {
				return item.data.filter((item) => item.checked).map((data) => data.friendsId)
			})
			return unnest(ids)
		})
		// 获取群名称
		const userNames = computed(() => {
			const ids = pageState.contacts.map((item) => {
				return item.data.filter((item) => item.checked).map((data) => data.friendsName)
			})
			return unnest(ids)
		})
		async function submit() {
			if (isEmpty(userIds.value)) {
				errorTips('请选择好友')
				return
			}
			pageState.loading = true
			const { success, data } = await API.blog.groupChat.createGroupChat.request({
				manager_id: userId,
				userIds: userIds.value,
				name: `${userNames.value}`.substring(0, 10),
			})
			pageState.loading = false
			if (success) {
				successTips(data.msg)
				BasicDataModule.getContacts()
				onCancel()
			}
		}
		function onCancel() {
			pageState.selectFriends = []
			emit('cancel')
		}
		return () => (
			<a-modal
				visible={props.visible}
				width="40%"
				height="59vh"
				onCancel={onCancel}
				onOk={submit}
				okText="确认"
				cancelText="取消"
				closable={false}
				confirmLoading={pageState.loading}
			>
				<div class="groupChatBody">
					<aside>
						<div class="friends_box">
							<ol class="user-list-box">
								{pageState.contacts.map((item) => {
									return (
										<li>
											<div class="letter">{item.letter}</div>
											<ul class="user-list">
												{item.data?.map((data) => {
													return (
														<div class="friends" onClick={() => selectFriends(data)}>
															<div class="checkbox-box">
																<a-checkbox v-model={[data.checked, 'checked']} disabled={data.disabled} />
															</div>
															<div class="friends_img">
																<div class="img_box">
																	<UserImg iconSize={35} imgSize={35} headimgurl={data.friends?.headimgurl} />
																</div>
															</div>
															<div class="info">
																<div class="name">
																	{friendsRemarksMap.value.get(String(data.friends?.id)) ?? data.friends?.username}
																</div>
															</div>
														</div>
													)
												})}
											</ul>
										</li>
									)
								})}
							</ol>
						</div>
					</aside>
					<article>
						<p class="title">
							<span>选择联系人</span>
							{!isEmpty(pageState.selectFriends) && <span>{`已选择${pageState.selectFriends.length}个联系人`}</span>}
						</p>
						<div class="friends_box">
							{map(
								(data) => (
									<div>
										<div class="friends">
											<div class="friends_img">
												<div class="img_box">
													<UserImg iconSize={50} imgSize={50} headimgurl={data.friends?.headimgurl} />
												</div>
											</div>
											<div class="info">
												<div class="name">
													{friendsRemarksMap.value.get(String(data.friends?.id)) ?? data.friends?.username}
												</div>
											</div>
											<CloseCircleFilled onClick={() => delFriends(data)} />
										</div>
									</div>
								),
								pageState.selectFriends ?? []
							)}
						</div>
					</article>
				</div>
			</a-modal>
		)
	},
})
